﻿using Acme.BookStore.RoomTable;
using AutoMapper;
using HIS;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Hosting;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp.Application.Services;
using Volo.Abp.Domain.Repositories;
using Volo.Abp.ObjectMapping;

namespace Acme.BookStore.RoomTypess
{
    [ApiExplorerSettings(GroupName = "v1")]
    public class RoomTypeServices : ApplicationService, IRoomTypeServices
    {
        private readonly IHttpContextAccessor _httpContextAccessor;

        private readonly IWebHostEnvironment _environment;
        public RoomTypeServices(IRepository<RoomType> roomTypeRepository, IWebHostEnvironment environment, IHttpContextAccessor httpContextAccessor)
        {
            RoomTypeRepository = roomTypeRepository;
            _environment = environment;
            _httpContextAccessor = httpContextAccessor;
        }

        public IRepository<RoomType> RoomTypeRepository { get; }

        /// <summary>
        /// 添加房型
        /// </summary>
        /// <param name="roomTypeDTO"></param>
        /// <returns></returns>
        [HttpPost("api/RoomType")]
        public async Task<APIResult> RoomTypeAdd(RoomTypeDTO roomTypeDTO)
        {
            try
            {
                //var roomTypeName = await RoomTypeRepository.FirstAsync(x => x.RoomName == roomTypeDTO.RoomName);
                //if (roomTypeName != null)
                //{
                //    return new APIResult()
                //    {
                //        Code = CodeEnum.error,
                //        Message = "房型已经存在"
                //    };
                //}
                RoomType roomType = ObjectMapper.Map<RoomTypeDTO, RoomType>(roomTypeDTO);
                await RoomTypeRepository.InsertAsync(roomType);
                if (roomType == null)
                {
                    return new APIResult()
                    {
                        Code = CodeEnum.error,
                        Message = "添加失败"
                    };
                }
                return new APIResult()
                {
                    Code = CodeEnum.success,
                    Message = "房型添加成功"
                };
            }
            catch (Exception)
            {

                throw;
            }
        }
        /// <summary>
        /// 删除房型
        /// </summary>
        /// <param name="Ids"></param>
        /// <returns></returns>
        [HttpDelete("api/RoomType")]
        public async Task<APIResult> RoomTypeDelete(string Ids)
        {
            try
            {
                var idList = Ids.Split(',').Select(x => Convert.ToInt32(x)).ToList();
                var roomTypes = await RoomTypeRepository.GetListAsync(x => idList.Contains(x.Id));

                if (roomTypes == null || !roomTypes.Any())
                {
                    return new APIResult()
                    {
                        Code = CodeEnum.error,
                        Message = "删除失败，未找到指定的房型"
                    };
                }

                foreach (var roomType in roomTypes)
                {
                    await RoomTypeRepository.DeleteAsync(roomType);
                }

                return new APIResult()
                {
                    Code = CodeEnum.success,
                    Message = "删除成功"
                };
            }
            catch (Exception ex)
            {
                return new APIResult()
                {
                    Code = CodeEnum.error,
                    Message = $"删除失败: {ex.Message}"
                };
            }
        }
        /// <summary>
        /// 上传图片
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        [HttpPost("api/RoomType/UploadImage")]
        public async Task<APIResult<string>> UploadRoomTypeImage(IFormFile file)
        {
            if (file == null || file.Length == 0)
            {
                return new APIResult<string>()
                {
                    Code = CodeEnum.error,
                    Message = "文件为空",
                    Data = null
                };
            }

            var uploadsFolder = Path.Combine(_environment.WebRootPath, "images");
            if (!Directory.Exists(uploadsFolder))
            {
                Directory.CreateDirectory(uploadsFolder);
            }

            var filePath = Path.Combine(uploadsFolder, file.FileName);
            var relativePath = Path.Combine("images", file.FileName);

            try
            {
                using (var stream = new FileStream(filePath, FileMode.Create))
                {
                    await file.CopyToAsync(stream);
                }
                var Request = _httpContextAccessor.HttpContext?.Request;
                var imageUrl = $"{Request.Scheme}://{Request.Host}/{relativePath.Replace("\\", "/")}";

                return new APIResult<string>()
                {
                    Code = CodeEnum.success,
                    Message = "图片上传成功",
                    Data = imageUrl
                };
            }
            catch (Exception ex)
            {
                return new APIResult<string>()
                {
                    Code = CodeEnum.error,
                    Message = $"图片上传失败: {ex.Message}",
                    Data = null
                };
            }
        }



        /// <summary>
        /// 查询房型
        /// </summary>
        /// <param name="RoomName"></param>
        /// <returns></returns>
        [HttpGet("api/RoomType")]
        public async Task<APIResult<List<RoomTypeDTO>>> RoomTypeShow(string RoomName, int Id)
        {
            try
            {
                var list = await RoomTypeRepository.GetListAsync(x => x.IsDeleted == false);
                if (!string.IsNullOrEmpty(RoomName))
                {
                   list = list.Where(x => x.RoomName == RoomName).ToList();
                }
                if (Id != 0)
                {
                    list = list.Where(x => x.Id == Id).ToList();
                }
                return new APIResult<List<RoomTypeDTO>>()
                {
                    Code = CodeEnum.success,
                    Message = "查询成功",
                    Data = ObjectMapper.Map<List<RoomType>, List<RoomTypeDTO>>(list.ToList())
                };
            }
            catch (Exception)
            {

                throw;
            }
        }
        /// <summary>
        /// 修改房型
        /// </summary>
        /// <param name="roomTypeUpdateDTO"></param>
        /// <returns></returns>
        [HttpPut("api/RoomType")]
        public async Task<APIResult> RoomTypeUpdate(RoomTypeUpdateDTO roomTypeUpdateDTO)
        {
            try
            {
                var roomType = await RoomTypeRepository.FirstOrDefaultAsync(x => x.Id == roomTypeUpdateDTO.Id);
                if (roomType == null)
                {
                    return new APIResult()
                    {
                        Code = CodeEnum.error,
                        Message = "房型未找到"
                    };
                }

                ObjectMapper.Map(roomTypeUpdateDTO, roomType);
                await RoomTypeRepository.UpdateAsync(roomType);

                return new APIResult()
                {
                    Code = CodeEnum.success,
                    Message = "房型修改成功"
                };
            }
            catch (Exception ex)
            {
                return new APIResult()
                {
                    Code = CodeEnum.error,
                    Message = $"修改失败: {ex.Message}"
                };
            }
        }

        /// <summary>
        /// 删除单个房型
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        [HttpDelete("api/RoomTypeSingle")]
        public async Task<APIResult> RoomTypeSingleDelete(int Id)
        {
            try
            {
                var roomtypes = await RoomTypeRepository.FirstOrDefaultAsync(x => x.Id == Id);
                if (roomtypes == null)
                {
                    return new APIResult()
                    {
                        Code = CodeEnum.error,
                        Message = "删除失败，未找到指定的房型"
                    };
                }
                await RoomTypeRepository.DeleteAsync(roomtypes);
                return new APIResult()
                {
                    Code = CodeEnum.success,
                    Message = "删除成功"
                };
            }
            catch (Exception)
            {

                throw;
            }
        }
    }
}
